import { loadModules, loadCss } from "esri-loader";

// 模块存放
const moduleStore: any = {};

/**
 * 初始化
 **/

export const init = () => {
  // arcgis api 配置
  const option = (window as any).esriConfig;
  loadCss(option.css);
  getModules(["esri/config"]).then(modules => {
    const [config] = modules;
    config.fontsUrl = option.font;
    config.log.level = "none";
  });
};

/**
 * @param modulePaths arcgis api 模块途径
 **/
export const getModules = (modulePaths: string[]) => {
  const promise = new Promise<any[]>((resolve, reject) => {
    const arr: Promise<any>[] = [];
    modulePaths.forEach(path => {
      arr.push(getModule(path));
    });
    Promise.all(arr)
      .then(modules => {
        resolve(modules);
      })
      .catch(e => {
        reject(e);
      });
  });
  return promise;
};

// 获取单个模块
export const getModule = (path: string) => {
  // arcgis api 配置
  const option = (window as any).esriConfig;
  const promise = new Promise<any>((resolve, reject) => {
    const name = path.split("/").pop() as string;
    if (moduleStore[name]) {
      resolve(moduleStore[name]);
    } else {
      loadModules([path], { url: option.api })
        .then(modules => {
          const module = modules[0];
          moduleStore[name] = module;
          resolve(module);
        })
        .catch(e => {
          reject({ msg: `load modules ${name} failed`, err: e });
        });
    }
  });
  return promise;
};
